package frog.lazy.framework.http.filter;

import cn.hutool.log.StaticLog;
import frog.lazy.framework.core.tools.BeanUtils;
import frog.lazy.framework.core.wrapper.HttpServletWrapper;
import frog.lazy.framework.http.dto.LoginInfoDTO;
import frog.lazy.framework.http.provider.ITokenProvider;
import frog.lazy.framework.http.provider.IRequestExtendProvider;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@AllArgsConstructor
public class TokenFilter extends OncePerRequestFilter {

    private ITokenProvider tokenProvider;
    private IRequestExtendProvider requestExtendProvider;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        HttpServletWrapper requestParameterWrapper = new HttpServletWrapper(httpServletRequest);
        LoginInfoDTO loginInfoDTO = tokenProvider.load(requestParameterWrapper);
        Map hashMap = new HashMap();
        hashMap.putAll(BeanUtils.beanToMap(loginInfoDTO, null));
        hashMap.putAll(requestExtendProvider.addExtendParams(requestParameterWrapper));
        requestParameterWrapper.addParameters(hashMap);
        StaticLog.debug(requestParameterWrapper.getRequestURI());
        filterChain.doFilter(requestParameterWrapper, httpServletResponse);
    }

}
